<template>
  <div class="signature-container">
    <div class="signature-header">
      <h2>电子手签确认</h2>
      <div class="approval-info">
        <p><span>订单ID：</span>{{ approvalId }}</p>
        <p><span>审批节点：</span>{{ approvalNodeName }}</p>
        <p><span>审批人：</span>{{ approvalUserName }}</p>
        <p><span>审批角色：</span>{{ approvalRoles }}</p>
        <p v-if="showAmount"><span>审批金额：</span>¥{{ approvalAmount }}</p>
      </div>
      <div v-if="showGoodsInfo" class="goods-info">
        <h3>货物信息</h3>
        <el-table :data="goodsList" border size="small" max-height="200">
          <el-table-column prop="name" label="货物名称" min-width="120"></el-table-column>
          <el-table-column prop="spec" label="规格型号" min-width="120"></el-table-column>
          <el-table-column prop="unit" label="单位" width="80" align="center"></el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="right">
            <template slot-scope="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="signature-pad-wrapper">
      <div class="signature-pad-container">
        <div style="height: 250px;"></div>
        <canvas ref="signaturePad" class="signature-pad"></canvas>
      </div>
      <div class="signature-buttons">
        <el-button type="danger" icon="el-icon-delete" size="small" @click="clearSignature">清除签名</el-button>
      </div>
    </div>

    <div class="signature-tip">
      <i class="el-icon-warning-outline"></i>
      <span>请在上方空白区域手写签名</span>
    </div>

    <div class="signature-footer">
      <el-button type="primary" @click="saveSignature" :loading="saving" :disabled="!signatureExists">确认签名</el-button>
      <el-button @click="cancelSignature">取消</el-button>
    </div>
  </div>
</template>

<script>
// 注意：需要安装 signature_pad 库
// npm install signature_pad --save
import SignaturePad from 'signature_pad';

export default {
  name: "SignaturePadComponent",
  props: {
    approvalId: {
      type: [String, Number],
      required: true
    },
    nodeId: {
      type: [String, Number],
      required: true
    },
    approvalNodeName: {
      type: String,
      default: '未知节点'
    },
    approvalUserName: {
      type: String,
      default: '未知用户'
    },
    approvalRoles: {
      type: String,
      default: '未知角色'
    },
    showAmount: {
      type: Boolean,
      default: false
    },
    approvalAmount: {
      type: [String, Number],
      default: 0
    },
    showGoodsInfo: {
      type: Boolean,
      default: false
    },
    goodsList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      signaturePad: null,
      signatureExists: false,
      saving: false,
      canvasInitialized: false
    };
  },
  mounted() {
    // 确保DOM已经渲染完毕再初始化画布
    this.$nextTick(() => {
      // 设置一个300ms的延迟，确保DOM完全渲染
      setTimeout(() => {
        this.initSignaturePad();
      }, 300);
    });

    // 监听窗口大小变化，调整canvas尺寸
    window.addEventListener('resize', this.resizeCanvas);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCanvas);

    // 清理SignaturePad实例
    if (this.signaturePad) {
      this.signaturePad.off();
      this.signaturePad = null;
    }
  },
  methods: {
    initSignaturePad() {
      const canvas = this.$refs.signaturePad;
      if (!canvas) {
        console.error('无法找到canvas元素');
        return;
      }

      // 先调整canvas尺寸
      this.resizeCanvas();

      try {
        // 如果已经初始化，先清理旧实例
        if (this.signaturePad) {
          this.signaturePad.off();
          this.signaturePad = null;
        }

        // 初始化signature_pad
        this.signaturePad = new SignaturePad(canvas, {
          backgroundColor: 'rgb(255, 255, 255)',
          penColor: 'rgb(0, 0, 0)',
          minWidth: 1,
          maxWidth: 2.5,
          velocityFilterWeight: 0.7 // 使签名更平滑
        });

        // 添加签名事件监听
        if (typeof this.signaturePad.addEventListener === 'function') {
          // 新版本API
          this.signaturePad.addEventListener("endStroke", () => {
            this.signatureExists = !this.signaturePad.isEmpty();
          });
        } else {
          // 旧版本API兼容
          const oldSignaturePad = this.signaturePad;
          const originalEndStroke = oldSignaturePad.endStroke;

          oldSignaturePad.endStroke = (...args) => {
            originalEndStroke.apply(oldSignaturePad, args);
            this.signatureExists = !oldSignaturePad.isEmpty();
          };
        }

        this.canvasInitialized = true;
        console.log('签名组件初始化成功');
      } catch (error) {
        console.error('签名组件初始化失败:', error);
        this.$message.error('初始化签名组件失败，请刷新页面重试');
      }
    },

    // 调整canvas尺寸
    resizeCanvas() {
      const canvas = this.$refs.signaturePad;
      if (!canvas) return;

      const container = canvas.parentElement;
      if (!container) return;

      // 保存当前签名数据
      let signatureData = null;
      if (this.signaturePad && !this.signaturePad.isEmpty()) {
        signatureData = this.signaturePad.toDataURL();
      }

      // 计算设备像素比
      const ratio = Math.max(window.devicePixelRatio || 1, 1);

      // 设置canvas尺寸
      canvas.width = container.offsetWidth * ratio;
      canvas.height = container.offsetHeight * ratio;

      // 设置canvas样式大小
      canvas.style.width = `${container.offsetWidth}px`;
      canvas.style.height = `${container.offsetHeight}px`;

      // 调整上下文比例
      const ctx = canvas.getContext("2d");
      ctx.scale(ratio, ratio);

      // 如果已有签名，则恢复
      if (this.signaturePad && signatureData) {
        this.signaturePad.clear();

        const image = new Image();
        const that = this;
        image.onload = function() {
          ctx.drawImage(image, 0, 0, canvas.width / ratio, canvas.height / ratio);
          that.signatureExists = true;
        };
        image.src = signatureData;
      } else if (this.signaturePad) {
        // 清空画布
        this.signaturePad.clear();
        this.signatureExists = false;
      }
    },

    // 清除签名
    clearSignature() {
      if (this.signaturePad) {
        this.signaturePad.clear();
        this.signatureExists = false;
      } else {
        // 如果签名组件尚未初始化，则尝试重新初始化
        this.initSignaturePad();
      }
    },

    // 保存签名
    saveSignature() {
      if (!this.canvasInitialized || !this.signaturePad) {
        this.$message.error('签名组件未初始化，请刷新页面重试');
        this.initSignaturePad(); // 尝试重新初始化
        return;
      }

      if (this.signaturePad.isEmpty()) {
        this.$message.warning('请先完成签名');
        return;
      }

      this.saving = true;

      try {
        // 获取签名图片的base64数据
        const signatureData = this.signaturePad.toDataURL('image/png');

        // 检查base64数据是否有效
        if (!signatureData || signatureData.length < 100) {
          throw new Error('生成的签名数据无效');
        }

        // 返回签名结果
        this.$emit('signed', {
          approvalId: this.approvalId,
          nodeId: this.nodeId,
          signatureData: signatureData,
          timestamp: new Date().toISOString()
        });

        this.saving = false;
      } catch (error) {
        console.error('保存签名失败:', error);
        this.$message.error('保存签名失败，请重新签名');
        this.saving = false;

        // 尝试重新初始化
        this.initSignaturePad();
      }
    },

    // 取消签名
    cancelSignature() {
      this.$confirm('确定取消签名？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('cancel');
      }).catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.signature-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  background-color: #f5f7fa;
}

.signature-header {
  margin-bottom: 20px;

  h2 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 18px;
    color: #303133;
    text-align: center;
  }

  .approval-info {
    background-color: #fff;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;

      span {
        font-weight: bold;
        margin-right: 5px;
      }
    }
  }

  .goods-info {
    margin-top: 15px;

    h3 {
      margin-top: 0;
      margin-bottom: 10px;
      font-size: 15px;
      color: #303133;
    }
  }
}

.signature-pad-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;

  .signature-pad-container {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 10px;
    overflow: hidden;
    position: relative;
    height: 250px;

    /* 重要：确保canvas能正确接收触摸事件 */
    touch-action: none;
    -ms-touch-action: none;

    .signature-pad {
      position: absolute;
      left: 0;
      top: 0;
      width: 100% !important;
      height: 100% !important;
      touch-action: none;
      -ms-touch-action: none;
      cursor: crosshair;
    }
  }

  .signature-buttons {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 15px;
  }
}

.signature-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  color: #909399;
  font-size: 14px;

  i {
    margin-right: 5px;
  }
}

.signature-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .signature-container {
    padding: 15px;
  }

  .signature-pad-wrapper {
    .signature-pad-container {
      height: 200px;
    }
  }
}
</style>
